package com.three.controller;

import com.three.utils.Doc2HtmlUtil;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

@Controller
public class Test03 {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @ResponseBody
    @RequestMapping("toPdf")
    public String toPdf(ServletResponse response, String filePath) {
        int HttpResult; // 服务器返回的状态
        URLConnection urlconn = null;
        try {
            URL url = new URL(filePath); // 创建URL
            urlconn = url.openConnection(); // 试图连接并取得返回状态码
            urlconn.connect();
            if (!(urlconn instanceof HttpURLConnection)) {
                return "该资源不是网络资源";
            }
            HttpURLConnection httpconn = (HttpURLConnection) urlconn;
            HttpResult = httpconn.getResponseCode();
            if (HttpResult != HttpURLConnection.HTTP_OK) {
                return "无法连接网络资源";
            }
        } catch (FileNotFoundException e) {
            return "无法找到网络资源";
//            e.printStackTrace();
        } catch (IOException e) {
            return "读取网络资源异常";
//            e.printStackTrace();
        }
        long startTime = System.currentTimeMillis();
        try {
            File docx = Doc2HtmlUtil.file2pdf(urlconn.getInputStream(), "D://", "docx");
            //写回
            ServletOutputStream outputStream = response.getOutputStream();
            InputStream in = new FileInputStream(docx);// 读取文件
            // copy文件
            IOUtils.copy(in, outputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return "未找到网络资源";
        } catch (IOException e) {
            e.printStackTrace();
            return "网络资源读取异常";
        } catch (Exception e) {
            e.printStackTrace();
            return "网络资源读取失败";
        }
        long endTime = System.currentTimeMillis();
        logger.info("程序运行时间：" + (endTime - startTime) + "ms");
        return "读取成功";
    }


}
